package com.zzt.video.task;

import com.zzt.video.model.dto.SeriesDto;
import com.zzt.video.model.entity.Series;
import com.zzt.video.service.SeriesService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SeriesRedisTask {

    @Autowired
    private SeriesService seriesService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 定时任务：每30分钟执行一次，更新每种type的最新10条数据到Redis
     */
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void updateSeriesCache() {
        log.info("开始更新Series缓存数据");

        // type有四种值：1, 2, 3, 4, 5
        for (int type = 1; type <= 5; type++) {
            try {
                // 查询指定type的最新10条数据
                List<Series> seriesList = seriesService.getLatestSeriesByType(type, 10);

                // 转换为Dto
                List<SeriesDto> dtoList = seriesList.stream()
                        .map(SeriesDto::new)
                        .collect(Collectors.toList());

                // 存入Redis，key为 series:latest:type:type值
                String redisKey = "series:latest:" + type;
                RBucket<List<SeriesDto>> seriesDtoBucket = redissonClient.getBucket(redisKey);
                seriesDtoBucket.set(dtoList);

                log.info("更新type={}的Series数据到Redis成功，共{}条", type, dtoList.size());
            } catch (Exception e) {
                log.error("更新type={}的Series数据到Redis失败", type, e);
            }
        }

        log.info("Series缓存数据更新完成");
    }

    /**
     * 定时任务：每10分钟执行一次，随机挑选每种type的10个视频作为"大家都在看"
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void updatePopularSeriesCache() {
        log.info("开始更新Series热门数据缓存");

        // type有四种值：1, 2, 3, 4, 5
        for (int type = 1; type <= 5; type++) {
            try {
                // 高性能随机查询指定type的10条数据
                List<Series> randomSeriesList = seriesService.getRandomSeriesByType(type, 10);

                // 转换为Dto
                List<SeriesDto> dtoList = randomSeriesList.stream()
                        .map(SeriesDto::new)
                        .collect(Collectors.toList());

                // 存入Redis，key为 series:popular:type:type值
                String redisKey = "series:popular:" + type;
                RBucket<List<SeriesDto>> seriesDtoBucket = redissonClient.getBucket(redisKey);
                seriesDtoBucket.set(dtoList);

                log.info("更新type={}的Series热门数据到Redis成功，共{}条", type, dtoList.size());
            } catch (Exception e) {
                log.error("更新type={}的Series热门数据到Redis失败", type, e);
            }
        }

        log.info("Series热门数据缓存更新完成");
    }
}
